﻿using System;
using System.ServiceModel;

namespace FirstFloor.Documents.IO
{
    /// <summary>
    /// A reference implementation of a package reader capable of consuming packages on-demand from WCF services.
    /// </summary>
    /// <remarks>
    /// This implementation uses the DocumentWcfService.svc service defined in the SampleBrowser.Web project.
    /// </remarks>
    public class WcfPackageReader
        : IPackageReader
    {
        private string documentName;
        private IDocumentWcfService service;

        /// <summary>
        /// Initializes a new instance of the <see cref="WcfPackageReader"/> class.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="documentName">Name of the document.</param>
        public WcfPackageReader(Uri uri, string documentName)
        {
            this.documentName = documentName;

            var factory = new ChannelFactory<IDocumentWcfService>(
                new BasicHttpBinding() { 
                    MaxReceivedMessageSize = int.MaxValue // no limit
                },
                new EndpointAddress(uri));

            this.service = factory.CreateChannel();
        }

        /// <summary>
        /// Initializes a new package part request.
        /// </summary>
        /// <param name="partUri">The part URI.</param>
        /// <returns>The part request.</returns>
        public IPackagePartRequest CreatePartRequest(Uri partUri)
        {
            if (partUri.IsInterleavingPieceUri()) {
                // interleaving pieces are never returned by WcfPackageReader
                return null;
            }

            return new WcfPackagePartRequest(this.service, documentName, partUri);
        }

        /// <summary>
        /// Resolves the specified part uri to a public accessible uri.
        /// </summary>
        /// <param name="partUri">The part URI.</param>
        /// <returns>The resolved URI.</returns>
        /// <remarks>If the package reader does not support public accessible uris, null is returned.</remarks>
        public Uri ResolvePartUri(Uri partUri)
        {
            return null;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            // nothing here
        }
    }
}
